package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Friend;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.FriendService;
import com.itheima.vo.ContactVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.UserCommentVo;
import com.itheima.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.swing.plaf.basic.BasicViewportUI;
import java.util.*;

@Component
public class MessageManager {

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private QuestionService questionService;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    // 打招呼（好友申请）
    public void strangerQuestions(Long jiarenId, String reply) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.查询userInfo
        UserInfo userInfo = userInfoService.findUserInfoById(userId);
        // 3.查询佳人的陌生人问题
        Question question = questionService.findByUserId(jiarenId);
        if (question == null) {
            question = new Question();
        }
        // 4.组装map
        Map map = new HashMap();
        map.put("userId", userId);
        map.put("huanXinId", "HX" + userId);
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", question.getStrangerQuestion());
        map.put("reply", reply);
        // 转json
        String json = JSON.toJSONString(map);
        // 5.调用环信模板发送消息
        huanXinTemplate.sendMsg("HX" + jiarenId, json);
    }

    @DubboReference
    private FriendService friendService;

    // 添加好友（联系人）
    public void addContacts(Long friendId) {
        // 1.获取我的id
        Long userId = UserHolder.get().getId();
        // 2.mongo加好友
        friendService.addContacts(userId, friendId);

        // 3.环信加好友
        huanXinTemplate.addContacts("HX" + userId, "HX" + friendId);
    }

    // 查看联系人
    public ResponseEntity findContactsByPage(Integer pageNum, Integer pageSize) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询联系人分页
        PageBeanVo pageBeanVo = friendService.findContactsByPage(userId, pageNum, pageSize);
        // 3.封装contactVo
        // 3.1 声明 voList
        List<ContactVo> voList = new ArrayList<>();
        // 3.2 获取 friendList
        List<Friend> friendList = (List<Friend>) pageBeanVo.getItems();
        // 3.3 遍历 friendList
        if (CollectionUtil.isNotEmpty(friendList)) {
            for (Friend friend : friendList) {
                // 创建vo
                ContactVo vo = new ContactVo();
                vo.setUserInfo(userInfoService.findUserInfoById(friend.getFriendId())); // 好友的基本信息
                vo.setUserId("HX" + friend.getFriendId()); // 好友的环信的

                // 添加到集合
                voList.add(vo);
            }
        }
        // 4.将vo设置到分页对象
        pageBeanVo.setItems(voList);

        // 5.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    // 根据环信id查询用户信息
    public ResponseEntity findUserInfoByHuanXinId(String huanxinId) {

        // 处理id的前缀HX
        huanxinId = huanxinId.replaceAll("HX", "");

        // 查询用户userInfo
        UserInfo userInfo = userInfoService.findUserInfoById(Long.parseLong(huanxinId));

        // 封装userInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo, userInfoVo);

        // 返回结果
        return ResponseEntity.ok(userInfoVo);
    }

    @DubboReference
    private CommentService commentService;

    // 根据类型查询
    public ResponseEntity findUserCommentVoByPage(Integer commentType, Integer pageNum, Integer pageSize) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询
        PageBeanVo pageBeanVo = commentService.findCommentTypeByPage(userId, commentType, pageNum, pageSize);
        // 3.封装userCommentVo
        // 3.1 声明voList
        List<UserCommentVo> voList = new ArrayList<>();
        // 3.2 获取 commentList
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        // 3.3 遍历
        if (CollectionUtil.isNotEmpty(commentList)) {
            for (Comment comment : commentList) {
                // 创建vo
                UserCommentVo vo = new UserCommentVo();
                // 查询用户信息
                UserInfo userInfo = userInfoService.findUserInfoById(comment.getUserId());
                vo.setId(userInfo.getId().toString()); // 操作人id
                vo.setNickname(userInfo.getNickname()); // 操作人昵称
                vo.setAvatar(userInfo.getAvatar()); // 操作人头像
                vo.setCreateDate(DateUtil.formatDateTime(new Date(comment.getCreated()))); // 操作时间

                // 添加到集合
                voList.add(vo);
            }
        }
        // 4.将vo设置到分页对象
        pageBeanVo.setItems(voList);

        // 5.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }
}
